package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @auther yuzehua
 * @date 2022/10/26 - 8:39
 */
public class Dws_TrafficChPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_TrafficChPageViewWindow().init(
                2010,
                2,
                "Dws_TrafficChPageViewWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 封装到一个 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚和
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_ch_page_view_window",
                        TrafficPageViewBean.class
                ));
    }

    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(
            SingleOutputStreamOperator<TrafficPageViewBean> beanStream){
        // NoKeyBy 聚合:  开窗: WindowAll 每维度, 所有的数据在一起聚和, 窗口处理函数的并行度只能是 1
        // keyBy 聚合: 并行度没有限制

        // 窗口处理函数:
        // 增量: sum max min   reduce  aggregate
        // 全量: process

        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                                .withIdleness(Duration.ofMillis(1))
                )
                .keyBy(TrafficPageViewBean::getCh)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TrafficPageViewBean>() {
                            @Override
                            public TrafficPageViewBean reduce(TrafficPageViewBean bean1,
                                                              TrafficPageViewBean bean2) throws Exception {
                                bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                                bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                                bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                                bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());
                                return bean1;
                            }
                        },
                        // 泛型一: 表示输入. 前面的聚和 结果 的类型.
                        new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                            @Override
                            public void process(String key,  // key 的值
                                                Context ctx,  // 上下文对象
                                                Iterable<TrafficPageViewBean> elements, // 存储的当前这个窗口最终聚合结果: 这个集和有且仅有一个值
                                                Collector<TrafficPageViewBean> out) throws Exception {
                                TrafficPageViewBean bean = elements.iterator().next();
                                // 补充窗口开始和结束
                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                Long svCt = bean.getSvCt();
                                if (svCt != 0) {
                                    bean.setPvAvgCt(bean.getPvCt() / svCt);
                                    bean.setDurAvgSum(bean.getDurSum() / svCt);
                                }else {
                                    bean.setPvAvgCt(bean.getPvCt());
                                    bean.setDurAvgSum(bean.getDurSum());
                                }

                                // 表示这个结果的统计时间
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);
                            }
                        }
                );

    }

    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {

                    private ValueState<String> dateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 给状态设置ttl
                        ValueStateDescriptor<String> desc = new ValueStateDescriptor<>("dateState", String.class);
                        desc.enableTimeToLive(new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.days(1)).build());
                        dateState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public TrafficPageViewBean map(JSONObject obj) throws Exception {

                        JSONObject common = obj.getJSONObject("common");
                        JSONObject page = obj.getJSONObject("page");

                        String ch = common.getString("ch");
                        Long ts = obj.getLong("ts");


                        Long pvCt = 1L;
                        Long durSum = page.getLong("during_time");

                        long svCt = 0L;
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            svCt = 1L;
                        }
                        Long uvCt = 0L;

                        // 状态中存储年月日, 如果来的数据的日期和状态不一样, 就是当天第一条 uvCt=1 更新状态,
                        // 否则就不是第一条
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)) {
                            // 更新状态
                            dateState.update(today);
                            uvCt = 1L;
                        }

                        Long pvAvgCt = 0L;
                        Long durAvgSum = 0L;


                        return new TrafficPageViewBean("", "",ch,
                                uvCt, svCt, pvCt,pvAvgCt, durSum,durAvgSum,
                                ts
                        );
                    }
                });
    }
}
